import mqtt, { MqttClient } from 'mqtt'
import {v4} from 'uuid';

class MqttOptions {
    connectTimeout: number;
    clientId: string;
    username: string;
    password: string;
    clean: boolean;

    constructor(username: string = "mqtt", password: string = "mqtt", clean: boolean = true, connectTimeout: number = 2000) {
        this.connectTimeout = connectTimeout
        this.clientId = v4()
        this.username = username
        this.password = password
        this.clean = clean
    }

    // constructor(username: string = "mqtt", password: string = "mqtt", clean: boolean = true, connectTimeout: number = 2000) {
    //     this.connectTimeout = connectTimeout
    //     this.clientId = uuid()
    //     this.username = username
    //     this.password = password
    //     this.clean = clean
    // }
}

class MqttService {
    static client: MqttClient | undefined;

    // 初始化连接
    static init(ip:string, options:MqttOptions, callback:Function=(topic:any,message:any)=>{console.log(message.toString())}) {
        this.client = mqtt.connect(ip, options)
        this.client.on("connect", ()=>{
            console.log("连接成功")
        })
        this.client.on("message", callback)
    }

    static AddMsgCallback(callback:Function){
        this.client?.on("message", callback)
    }

    // 订阅
    static subscribe(topic:string|string[]){
        setTimeout(()=>{
            if(typeof this.client != undefined){
                this.client?.subscribe(topic, (err:any) => {
                    if (!err) {
                    }else{
                        console.log(err)
                    }
                })
            }
        },300)
    }

    // 取消订阅
    static unsubscribe(topic:string|string[]){
        this.client?.unsubscribe(topic, (err:any) => {
            if (!err) {
                console.log(`取消订阅${topic}成功`)
            }
        })
    }

    // 结束连接(好像没有用)
    static end(){
        this.client?.end()
    }

    // 重新连接
    static reconnect(){
        this.client?.reconnect()
    }
}

export {
    MqttOptions,
    MqttService
}